package com.zj.controller;

import com.zj.i18n.I18nCode;
import com.zj.pojo.Apple;
import com.zj.pojo.Result;
import com.zj.services.BaseService;
import com.zj.i18n.I18nUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/apple")
public class AppleI18NController {
    private static Logger log = LoggerFactory.getLogger(AppleI18NController.class);

    @Autowired
    private BaseService service;
    @Autowired
    private MessageSource source;


    @GetMapping("/{id}")
    public Result getApple(@PathVariable int id) {
//        int idd=2/0;
        log.info("请求getApple进入" + id);
        Apple apple = service.getAppleById(id);
        //LocaleContextHolder是一个持有器，springmvc底层自动将LocaleResolver中语言设置进去
        String message = source.getMessage(I18nCode.APPLE_QUERY_OK.getMsg(), null, LocaleContextHolder.getLocale());
        return new Result(HttpStatus.OK.value(), message, apple);
    }

    @PostMapping("/add")
    public Result addApple(@RequestBody Apple apple) {
        log.info("请求addApple进入" + apple.toString());
        int size = service.insertApples(apple);
        return new Result<>(HttpStatus.OK.value(), I18nUtil.getMessage(I18nCode.APPLE_ADD_OK.getMsg(), null), size);
    }

    @PutMapping("/{id}")
    public Result updateApple(@PathVariable int id, @RequestBody Apple apple) {
        log.info("请求updateApple进入" + apple.toString());

        List<Apple> apppool = service.updateAppleById(id, apple);
        return new Result<>(HttpStatus.OK.value(), I18nUtil.getMessage(I18nCode.APPLE_UPDATE_OK.getMsg(), null), apppool);
    }

    @GetMapping("/all")
    public Result getAll() {
        log.info("请求getAll进入");

        List<Apple> apppool = service.getApppool();
        return new Result<>(HttpStatus.OK.value(), I18nCode.APPLE_QUERYALL_OK, apppool);
    }

    @DeleteMapping("/{id}")
    public Result deleteApple(@PathVariable int id) {
        log.info("请求deleteApple进入" + id);

        List<Apple> apppool = service.deleteApple(id);
        return new Result<>(HttpStatus.OK.value(), I18nUtil.getMessage(I18nCode.APPLE_DELETE_OK.getMsg(), null), apppool);

    }
}
